# 创建仪表盘页面组件
<template>
  <div class="page-container">
    <header class="header">
      <div class="header-content">
        <router-link to="/" class="logo">
          <h1>匿名社交网络系统</h1>
        </router-link>
        <div class="user-info">
          <el-dropdown @command="handleCommand">
            <div class="user-dropdown">
              <el-avatar :size="32" :src="userStore.userInfo?.avatar">
                {{ userStore.userInfo?.nickname?.[0] || userStore.userInfo?.username?.[0] }}
              </el-avatar>
              <span class="username">{{ userStore.userInfo?.nickname || userStore.userInfo?.username }}</span>
              <el-icon><arrow-down /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'USER'" command="profile">
                  <el-icon><user /></el-icon>个人资料
                </el-dropdown-item>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'USER'" command="friends">
                  <el-icon><user-filled /></el-icon>关注列表
                </el-dropdown-item>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'ADMIN'" command="dashboard">
                  <el-icon><odometer /></el-icon>仪表盘
                </el-dropdown-item>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'ADMIN'" command="k-anonymity">
                  <el-icon><Setting /></el-icon>K匿名配置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><switch-button /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </header>

    <main class="main-content">
      <div class="content-wrapper">
        <el-card class="dashboard-card">
          <template #header>
            <h2 class="card-title">仪表盘</h2>
          </template>

          <el-row :gutter="20">
            <!-- 总数据统计 -->
            <el-col :span="24">
              <h3 class="section-title">总数据统计</h3>
              <el-row :gutter="20" class="stat-cards">
                <el-col :span="6">
                  <el-card shadow="hover" class="stat-card">
                    <template #header>
                      <div class="stat-header">
                        <el-icon><user /></el-icon>
                        <span>总用户数</span>
                      </div>
                    </template>
                    <div class="stat-value">{{ stats.totalUsers || 0 }}</div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card shadow="hover" class="stat-card">
                    <template #header>
                      <div class="stat-header">
                        <el-icon><document /></el-icon>
                        <span>总动态数</span>
                      </div>
                    </template>
                    <div class="stat-value">{{ stats.totalPosts || 0 }}</div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card shadow="hover" class="stat-card">
                    <template #header>
                      <div class="stat-header">
                        <el-icon><chat-dot-round /></el-icon>
                        <span>总评论数</span>
                      </div>
                    </template>
                    <div class="stat-value">{{ stats.totalComments || 0 }}</div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card shadow="hover" class="stat-card">
                    <template #header>
                      <div class="stat-header">
                        <el-icon><star /></el-icon>
                        <span>总点赞数</span>
                      </div>
                    </template>
                    <div class="stat-value">{{ stats.totalLikes || 0 }}</div>
                  </el-card>
                </el-col>
              </el-row>
            </el-col>

            <!-- 今日数据统计 -->
            <el-col :span="24" style="margin-top: 20px;">
              <h3 class="section-title">今日数据统计</h3>
              <el-row :gutter="20" class="stat-cards">
                <el-col :span="6">
                  <el-card shadow="hover" class="stat-card">
                    <template #header>
                      <div class="stat-header">
                        <el-icon><user /></el-icon>
                        <span>日活跃用户</span>
                      </div>
                    </template>
                    <div class="stat-value">{{ stats.dailyActiveUsers || 0 }}</div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card shadow="hover" class="stat-card">
                    <template #header>
                      <div class="stat-header">
                        <el-icon><document /></el-icon>
                        <span>今日动态</span>
                      </div>
                    </template>
                    <div class="stat-value">{{ stats.dailyPosts || 0 }}</div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card shadow="hover" class="stat-card">
                    <template #header>
                      <div class="stat-header">
                        <el-icon><chat-dot-round /></el-icon>
                        <span>今日评论</span>
                      </div>
                    </template>
                    <div class="stat-value">{{ stats.dailyComments || 0 }}</div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card shadow="hover" class="stat-card">
                    <template #header>
                      <div class="stat-header">
                        <el-icon><star /></el-icon>
                        <span>今日点赞</span>
                      </div>
                    </template>
                    <div class="stat-value">{{ stats.dailyLikes || 0 }}</div>
                  </el-card>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-card>

        <!-- 图表展示 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <!-- 用户和内容统计对比 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <h3>用户与内容统计</h3>
                </div>
              </template>
              <div ref="userContentChart" class="chart"></div>
            </el-card>
          </el-col>

          <!-- 互动数据统计对比 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <h3>互动数据统计</h3>
                </div>
              </template>
              <div ref="interactionChart" class="chart"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 7日数据分析 -->
        <el-row style="margin-top: 20px;">
          <el-col :span="24">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <h3>7日数据分析</h3>
                </div>
              </template>
              <div ref="weeklyChart" class="chart"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  ArrowDown,
  User,
  UserFilled,
  SwitchButton,
  Document,
  ChatDotRound,
  Star,
  Odometer,
  Setting
} from '@element-plus/icons-vue'
import { getDashboardStats } from '../api'

const router = useRouter()
const userStore = useUserStore()
const stats = ref({})

// 图表引用
const userContentChart = ref(null)
const interactionChart = ref(null)
const weeklyChart = ref(null)

// 统计卡片配置
const statCards = [
  { title: '总用户数', icon: 'User', key: 'totalUsers' },
  { title: '总动态数', icon: 'Document', key: 'totalPosts' },
  { title: '总评论数', icon: 'ChatDotRound', key: 'totalComments' },
  { title: '总点赞数', icon: 'Star', key: 'totalLikes' }
]

// 初始化用户与内容统计图表
const initUserContentChart = () => {
  const chart = echarts.init(userContentChart.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: [
          { value: stats.value.totalUsers, name: '用户数' },
          { value: stats.value.totalPosts, name: '动态数' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化互动数据统计图表
const initInteractionChart = () => {
  const chart = echarts.init(interactionChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['评论', '点赞']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '总数',
        type: 'bar',
        data: [stats.value.totalComments, stats.value.totalLikes]
      }
    ]
  }
  chart.setOption(option)
}

// 初始化7日数据分析图表
const initWeeklyChart = () => {
  const chart = echarts.init(weeklyChart.value)
  const dates = stats.value.weeklyStats?.map(item => item.date) || []
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['活跃用户', '新增动态', '新增评论', '新增点赞']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '活跃用户',
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          width: 0
        },
        showSymbol: false,
        areaStyle: {
          opacity: 0.8,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgb(128, 255, 165)'
            },
            {
              offset: 1,
              color: 'rgb(1, 191, 236)'
            }
          ])
        },
        emphasis: {
          focus: 'series'
        },
        data: stats.value.weeklyStats?.map(item => item.activeUsers) || []
      },
      {
        name: '新增动态',
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          width: 0
        },
        showSymbol: false,
        areaStyle: {
          opacity: 0.8,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgb(0, 221, 255)'
            },
            {
              offset: 1,
              color: 'rgb(77, 119, 255)'
            }
          ])
        },
        emphasis: {
          focus: 'series'
        },
        data: stats.value.weeklyStats?.map(item => item.posts) || []
      },
      {
        name: '新增评论',
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          width: 0
        },
        showSymbol: false,
        areaStyle: {
          opacity: 0.8,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgb(55, 162, 255)'
            },
            {
              offset: 1,
              color: 'rgb(116, 21, 219)'
            }
          ])
        },
        emphasis: {
          focus: 'series'
        },
        data: stats.value.weeklyStats?.map(item => item.comments) || []
      },
      {
        name: '新增点赞',
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          width: 0
        },
        showSymbol: false,
        areaStyle: {
          opacity: 0.8,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgb(255, 191, 0)'
            },
            {
              offset: 1,
              color: 'rgb(224, 62, 76)'
            }
          ])
        },
        emphasis: {
          focus: 'series'
        },
        data: stats.value.weeklyStats?.map(item => item.likes) || []
      }
    ]
  }
  chart.setOption(option)
}

// 初始化所有图表
const initCharts = () => {
  nextTick(() => {
    initUserContentChart()
    initInteractionChart()
    initWeeklyChart()
  })
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await getDashboardStats()
    stats.value = response.data
    initCharts()
  } catch (error) {
    ElMessage.error('获取统计数据失败')
  }
}

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'friends':
      router.push('/friends')
      break
    case 'dashboard':
      router.push('/admin/dashboard')
      break
    case 'k-anonymity':
      router.push('/admin/k-anonymity')
      break
    case 'logout':
      userStore.logout()
      router.push('/login')
      break
  }
}

// 监听窗口大小变化，重新调整图表大小
const handleResize = () => {
  const charts = [
    echarts.getInstanceByDom(userContentChart.value),
    echarts.getInstanceByDom(interactionChart.value),
    echarts.getInstanceByDom(weeklyChart.value)
  ]
  charts.forEach(chart => chart?.resize())
}

onMounted(() => {
  fetchStats()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  height: 100%;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  text-decoration: none;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  color: var(--primary-color);
}

.user-info {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-dropdown:hover {
  background-color: var(--background-color);
}

.username {
  margin: 0 8px;
  color: var(--text-color);
}

.main-content {
  padding-top: 80px;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.dashboard-card {
  margin-bottom: 20px;
}

.section-title {
  margin: 0 0 20px;
  font-size: 16px;
  color: var(--text-color);
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: var(--text-color);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--primary-color);
  text-align: center;
  margin-top: 10px;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 5px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart {
  height: 400px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: var(--text-color);
}

.stat-card {
  height: 100%;
  margin-bottom: 20px;
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: var(--text-color);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--primary-color);
  text-align: center;
  margin-top: 10px;
}

@media screen and (max-width: 768px) {
  .content-wrapper {
    padding: 0 10px;
  }

  .chart {
    height: 300px;
  }

  .el-col {
    margin-bottom: 20px;
  }
}
</style> 